package controller;

import gui.OptionPane;

import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Date;

import model.PlayerInterface;
import model.UserInterface;
import toolkit.Debug;

public class Register extends Controller
{
	private String username;
	
	private char[] password, confirmPassword;
	
	private Date birthday;
	
	public Register()
	{
		setView(new view.Register(this));
	}
	
	public void setUsername(String username)
	{
		this.username = username;
	}

	public void setPassword(char[] password, char[] confirmPassword)
	{
		this.password = password;
		this.confirmPassword = confirmPassword;
	}
	
	public void setBirthday(Date birthday)
	{
		this.birthday = birthday;
	}
	
	public void register()
	{
		PlayerInterface player = null;
		
		if (username.isEmpty())
		{
			OptionPane.showError("Empty username", "Please fill in a username.");
		}
		else if (password.length == 0)
		{
			OptionPane.showError("Empty password", "Please fill in a password.");
		}
		else if (!Arrays.equals(password, confirmPassword))
		{
			OptionPane.showError("Different passwords", "The password confirm does not match the password.");
		}
		else if (birthday == null)
		{
			OptionPane.showError("Empty birthday", "Please fill in your day of birth.");
		}
		else
		{
			try
			{
				
				if (userRemote.getUserByUsername(this.username) != null)
				{
					OptionPane.showError("User already exists", "The given username has already been found in the database. Make sure that you fill in a unique username.");
				}
				else
				{
					player = userRemote.newPlayer(username);
				
					player.setPassword(password);
					player.setBirthday(birthday);
				
					userRemote.storeUser(player);
				
					forward(new controller.Login());
				}
			}
			catch (RemoteException e)
			{
				Debug.log(e);
				
				OptionPane.showError("Error", "Something went wrong when trying to register.");
			}
		}
	}
	
	public void cancel()
	{
		forward(new controller.Login());
	}
}
